<?php

/**
 * Created by JetBrains PhpStorm.
 * User: superx
 * Date: 7/31/13
 * Time: 1:48 PM
 * To change this template use File | Settings | File Templates.
 */
abstract class My_Task extends Core_Task {

    protected $_pid;
    protected $_host;
    protected $_id;


    public function run() {
        call_user_func([$this, $this->params['call']]);
    }

    public function paramRules() {
        return [
            'call' => [
                'default' => '_run'
            ]
        ];
    }

    public function println($str = '', $log = true) {
        $str = "[{$this->_pid}@{$this->_host}] " . $str;
        parent::println($str, $log);
    }

    public function __construct($request) {
        parent::__construct($request);

        $this->_host = php_uname('n');
        $this->_pid = posix_getpid();
        $data = new Model_WorkerStatus();
        $data->pid = $this->_pid;
        $data->host = $this->_host;
        $data->name = $request->getCmd();
        $data->last_activity = date('Y-m-d H:i:s');
        $data->ext = 'Just Started';
        $this->_id = Dao_WorkerStatus::getInstance()->insert($data);
        $this->println("Just Started");
    }

    public function updateStatus($info = 'Work Work ...', $status = Model_WorkerStatus::STATUS_OK, $log = false) {
        $this->println("{$info}", $log);
        Dao_WorkerStatus::getInstance()->update(array(
            'last_activity' => date('Y-m-d H:i:s'),
            'ext' => $info,
            'status' => $status
        ), $this->_id);
    }

    public function checkSignal() {
        $row = Dao_WorkerStatus::getInstance()->find($this->_id);
        if (!$row) {
            //out of control
            exit();
        }
        $this->println("Checking Signal ...", false);
        switch ($row->signal) {
            case Model_WorkerStatus::SIG_KILL:
                $this->updateStatus('Die Peacefully, Bye Bye...', Model_WorkerStatus::STATUS_DIED, true);
                exit();
                break;
            default:
                $this->updateStatus();
                break;
        }
    }

    public function prepareToDie() {
        Dao_WorkerStatus::getInstance()->update(array('`signal`' => Model_WorkerStatus::SIG_KILL), $this->_id);
    }

    public function sendAlert($msg) {
        Lib_Util::sendSms(Core_Config::get('worker.watchers.mobile'), '[ENV ' . ENV . ']' . $msg);
    }
}